package cn.zjitc.craft.servlet;

import cn.zjitc.craft.domain.User;
import cn.zjitc.craft.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserServlet extends HttpServlet {

    private UserService userService;
    @Override
    public void init() throws ServletException {
        super.init();
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        this.userService = springContext.getBean(UserService.class);
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if ("save".equals(method)) {
            save(request, response);
        }
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        User user =new User();
        user.setName(name);
        user.setPassword(password);
        userService.save(user);
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("<h2>保存成功</h2>");
    }
}
